<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>City预测页面</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/trainingResult.css' %}">
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>

    <script>//实现隐藏导航的效果
    toggleNavbar = function () {
        const navbar = document.getElementById('navbar');
        const mainContent = document.getElementById('main-content');
        const toggleButton = document.getElementById('toggleButton'); // 获取按钮元素

        if (navbar.classList.contains('hidden')) {
            navbar.classList.remove('hidden'); // 显示导航
            mainContent.style.width = '80%'; // 恢复主内容宽度
            toggleButton.innerHTML = '<img  class="button4-icon" src="{% static 'icons/chevron-left.svg' %}" alt="城市图标">'; // 切换按钮文字
        } else {
            navbar.classList.add('hidden'); // 隐藏导航
            mainContent.style.width = '100%'; // 主内容占满整个页面
            toggleButton.innerHTML = '<img  class="button4-icon" src="{% static 'icons/chevron-right.svg' %}" alt="城市图标">'; // 切换按钮文字
        }
    }
    </script>
<body>

<div class="sidebar" id="navbar"> <!--导航-->
  <img class="logo" src="{% static 'icons/logo.jpg' %}" alt="logo图标">
    <p class="title">SecTraffic</p>
    <p class="underline"></p>
    <div>
        <a href="{% url 'training' %}">
            <button class="button1">
                <img class="button1-icon" src="{% static 'icons/building.png' %}" alt="城市图标">
                <span> City----我要训练</span>
            </button>
        </a>
    </div>
    <div>
        <a href="{% url 'predicting' %}">
            <button class="button1">
                <img class="button1-icon" src="{% static 'icons/building.png' %}" alt="城市图标">
                <span> City----我要预测</span>
            </button>
        </a>
    </div>
</div>


<div class="content" id="main-content">
    {#  实现主页面#}
    <p>
        <!-- 点击按钮以隐藏或显示导航 -->
        <button class="button4" onclick="toggleNavbar()" id="toggleButton">
            <img class="button4-icon" src="{% static 'icons/chevron-left.svg' %}" alt="隐藏">
        </button>
    </p>

    <h1 class="Table-text">预测地图</h1>
    <div id="map" style="width: 100%;height: 800px; margin: 20px 0;z-index: 0;flex-grow: 1; /* 使地图容器自适应剩余空间 */"></div>

    <button class="button2" onClick="location.href='/City/predicting'">预<br>测<br>结<br>果</button>

    <button class="button3">预<br>测<br>地<br>图</button>

</div>

<script>
    // 从 Django 模板传递的城市坐标数据
    const cityName = "{{ city_name }}";  // 从后端传递的城市名称
    console.log("City Name:", cityName);
    const cityCoordinates = {
        "上海": [31.2304, 121.4737],
        "北京": [39.9042, 116.4074],
        "广州": [23.1291, 113.2644],
        "深圳": [22.5431, 114.0579],
    };

    // 检查是否有有效的城市坐标
    if (cityName && cityCoordinates[cityName]) {
        const cityCenter = cityCoordinates[cityName];

        // 初始化地图
        const map = L.map('map').setView(cityCenter, 12);

        // 添加地图瓦片层
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        // 添加一个标记
        L.marker(cityCenter).addTo(map).bindPopup(cityName).openPopup();
    } else {
        console.error('城市信息无效，无法加载地图');
    }


    // 示例Node数据（实际数据应该从后端获取）
    const nodes = [
        {name: 'Node 1', uploaded: false, requested: false, result: ''},
        {name: 'Node 2', uploaded: true, requested: true, result: ''},
        {name: 'Node 3', uploaded: false, requested: false, result: ''},
        {name: 'Node 4', uploaded: true, requested: false, result: ''},
        {name: 'Node 5', uploaded: true, requested: true, result: ''},
        {name: 'Node 6', uploaded: false, requested: true, result: ''},
        {name: 'Node 7', uploaded: true, requested: false, result: ''},
        {name: 'Node 8', uploaded: false, requested: true, result: ''},
        {name: 'Node 9', uploaded: true, requested: true, result: ''},
        {name: 'Node 10', uploaded: false, requested: false, result: ''},
        {name: 'Node 11', uploaded: false, requested: false, result: ''},
        {name: 'Node 12', uploaded: false, requested: false, result: ''},
        {name: 'Node 13', uploaded: true, requested: true, result: ''},
    ];

    // 初始化表格
    function loadTable() {
        const tableBody = document.querySelector('#predictionTable tbody');
        tableBody.innerHTML = ''; // 清空现有行

        nodes.forEach((node, index) => {
            const row = document.createElement('tr');

            // Node节点名称
            const nameCell = document.createElement('td');
            nameCell.textContent = node.name;
            row.appendChild(nameCell);

            // 是否上传数据
            const uploadCell = document.createElement('td');
            uploadCell.textContent = node.uploaded ? '是' : '否';
            row.appendChild(uploadCell);

            // 是否发送预测请求
            const requestCell = document.createElement('td');
            requestCell.textContent = node.requested ? '是' : '否';
            row.appendChild(requestCell);

            // 预测按钮
            const predictCell = document.createElement('td');
            const predictButton = document.createElement('button');
            predictButton.textContent = '预测';
            predictButton.className = 'button-predict'; // 添加样式类
            predictButton.disabled = !(node.uploaded && node.requested); // 根据条件启用或禁用
            predictButton.onclick = () => predict(node.name, index);
            predictCell.appendChild(predictButton);
            row.appendChild(predictCell);

            // 预测结果
            const resultCell = document.createElement('td');
            resultCell.textContent = node.result;
            row.appendChild(resultCell);

            tableBody.appendChild(row);
        });
    }

    // 执行预测
    function predict(nodeName, index) {
        if (nodes[index].uploaded && nodes[index].requested) {
            // 模拟预测结果
            const predictionResult = `预测结果：${(Math.random() * 100).toFixed(2)}`;
            {#随机生成一个数据#}
            nodes[index].result = predictionResult; // 更新预测结果
            loadTable(); // 重新加载表格以显示结果
        } else {
            alert('请确保已上传数据并发送预测请求。');
        }
    }

    // 页面加载时初始化表格
    window.onload = loadTable;

</script>
<script>
    // 实现下载文件（实时预测文件）
    function downloadTableData() {
        let table = document.getElementById('predictionTable');
        let csv = [];
        let rows = table.rows;

        for (let i = 0; i < rows.length; i++) {
            let cols = rows[i].querySelectorAll('td, th');
            let row = Array.from(cols).map(col => col.innerText).join(',');
            csv.push(row);
        }

        let csvString = csv.join('\n');
        let blob = new Blob([csvString], {type: 'text/csv;charset=utf-8;'});
        let link = document.createElement('a');
        link.setAttribute('href', URL.createObjectURL(blob));
        link.setAttribute('download', 'predicting-data.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    document.getElementById('downloadBtn').addEventListener('click', downloadTableData);
</script>
</body>
</html>